package Dao;

import Back.MAP;
import org.example.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class dt {
    // MySQL数据库连接参数
    private String url = "jdbc:mysql://localhost:3306/db?user=root&password=123456";
    private Connection conn;

    // 1. 建立数据库连接
    public void connect() {
        try {
            // 加载 JDBC 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立连接
            conn = DriverManager.getConnection(url);
            System.out.println("✅ 数据库连接成功！");
        } catch (Exception e) {
            System.err.println("❌ 连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 3. 关闭数据库连接
    public void closeConnection() {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                System.out.println("✅ 数据库连接已关闭！");
            }
        } catch (SQLException e) {
            System.err.println("❌ 关闭连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //4.插入到回放数据库中
    //TODO 修改参数
    public void insert(String name,int width,int height,String obstacles,int count,int maxtime,int mintime,String userid)
    {
        String sql = "INSERT INTO replay_record (replay_name, map_width, map_height, obstacles, car_count,max_time,min_time,id) "
                + "VALUES (?, ?, ?, ?, ?,?,?,?)";
        try (PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            // 设置参数
            preparedStatement.setString(1, name);
            preparedStatement.setInt(2, width);
            preparedStatement.setInt(3, height);
            preparedStatement.setString(4, obstacles);
            preparedStatement.setInt(5, count);
            preparedStatement.setInt(6, maxtime);
            preparedStatement.setInt(7, mintime);
            preparedStatement.setString(8, userid);
            // 执行插入操作
            preparedStatement.executeUpdate();
            System.out.println("✅ 数据插入成功！");
        } catch (SQLException e) {
            System.err.println("❌ 插入数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //5.插入到车的路径当中去
    public void addcar(String name,int id,String path,String userid)
    {
        String sql = "INSERT INTO car_path (car_id,replay_name,car_path,userid) "
                + "VALUES (?, ?, ?,?)";
        try (PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            // 设置参数
            preparedStatement.setInt(1, id);
            preparedStatement.setString(2, name);
            preparedStatement.setString(3, path);
            preparedStatement.setString(4, userid);
            // 执行插入操作
            preparedStatement.executeUpdate();
            System.out.println("✅ 数据插入成功！");
        } catch (SQLException e) {
            System.err.println("❌ 插入数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 6. 加载回放名称（根据用户角色和ID过滤）
    public List<String> getReplayNames(User currentUser) {
        List<String> replayNames = new ArrayList<>();

        // 构建基础SQL
        String sql = "SELECT replay_name FROM replay_record";

        // 根据用户角色添加条件
        if (currentUser != null && "student".equals(currentUser.getRole())) {
            sql += " WHERE id = ?"; // 学生只能查看自己的回放
        } else if (currentUser == null || !"teacher".equals(currentUser.getRole())) {
            // 非教师角色或未登录用户返回空列表
            return replayNames;
        }

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            // 设置学生用户的参数
            if (currentUser != null && "student".equals(currentUser.getRole())) {
                stmt.setString(1, currentUser.getId());
            }

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    String replayName = rs.getString("replay_name");
                    replayNames.add(replayName);
                }
            }
        } catch (SQLException e) {
            System.err.println("❌ 查询回放名称失败: " + e.getMessage());
            e.printStackTrace();
        }
        return replayNames;
    }

    /**
     * 根据回放名称查询地图数据
     */
    public MAP getnewmap(String name) {
        String sql = "SELECT map_width, map_height, obstacles, car_count,max_time,min_time FROM replay_record WHERE replay_name = ?";

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, name); // 设置查询参数
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                int width = rs.getInt("map_width");
                int height = rs.getInt("map_height");
                String obstacles = rs.getString("obstacles");
                int carCount = rs.getInt("car_count");
                int max_time=rs.getInt("max_time");
                int min_time=rs.getInt("min_time");
                // 返回封装好的 MAP 对象
                return new MAP(width, height, obstacles, carCount,max_time,min_time);
            } else {
                System.out.println("❌ 未找到 replay_name = " + name + " 的记录");
                return null;
            }
        } catch (SQLException e) {
            System.err.println("❌ 查询地图数据失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


    //7.加载小车回放路径
    public String carpath(String name, int id) {
        String sql = "SELECT car_path FROM car_path WHERE replay_name = ? AND car_id = ?";

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, name); // 设置 replay_name 参数
            stmt.setInt(2, id);       // 设置 car_id 参数

            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getString("car_path"); // 返回路径字符串
            } else {
                System.out.println("❌ 未找到符合条件的路径数据：replay_name=" + name + ", car_id=" + id);
                return null;
            }
        } catch (SQLException e) {
            System.err.println("❌ 查询小车路径失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    //将所有小车的坐标绘制为二维数组，并且按照时间来排序的！！！！
    public String[][] createCarPathArray(String replayName, int carcount,int last) {
        String[][] arr = new String[carcount + 1][]; // 索引从 1 开始

        for (int carId = 1; carId <= carcount; carId++) {
            String path = carpath(replayName, carId); // 获取路径
            if (path == null || path.isEmpty()) {
                System.out.println("❌ 小车 " + carId + " 没有路径数据");
                continue;
            }
            //timeSteps=score:member
            String[] timeSteps = path.split("\\+"); // 使用正则表达式分割 "+"
            arr[carId] = new String[last+1]; // 初始化当前小车的时间步长度

            for (int i = 0; i < timeSteps.length; i++) {
                String step = timeSteps[i];
                //step=score:member
                String[] parts = step.split(":"); // 分割 score 和 member
                //parts[0]=score;
                //parts[1]=member;
                if (parts.length >= 2) {
                    String score = parts[0];
                    String coordinate = parts[1].trim(); // 坐标值如 "2 3"

                    // 将坐标放入对应 score 的位置
                    try {
                        int scoreIndex =(int) Double.parseDouble(score);
                        arr[carId][scoreIndex] = coordinate;
                    } catch (NumberFormatException e) {
                        System.err.println("⚠️ score 格式错误：" + score);
                    }
                } else {
                    System.out.println("⚠️ 路径格式错误：" + step);
                }
            }
        }
        return arr;
    }

}
